<template>
  <div
    id="container"
    style="width: 100%; height: 600px; background-color: #053c7d"
  ></div>
</template>

<script setup>
import G6 from "@antv/g6";

const { Util } = G6;
import { useRouter } from "vue-router";
const router = useRouter();
import { useSubjectStore } from "../../store/subject";
let subjectStore = useSubjectStore();

const splitStringByMaxLength = (str) => {
  let result = [];
  if (str.length <= 3) {
    result.push(str);
    return result;
  }
  let firstPartLength = 0;

  if (str.length % 2 === 0) {
    // 字符串长度是偶数，直接平分
    firstPartLength = str.length / 2;
  } else {
    // 字符串长度是奇数，第一段比第二段少一个字符
    firstPartLength = Math.ceil(str.length / 2) - 1;
  }

  result.push(str.substring(0, firstPartLength));
  result.push(str.substring(firstPartLength));

  return result;
};
onMounted(() => {
  G6.registerNode("dice-mind-map-root", {
    draw: (cfg, group) => {
      const labelList = splitStringByMaxLength(cfg.label);
      const wrapWidth =
        Util.getTextSize(labelList[labelList.length - 1], 20)[0] + 60;
      const width =
        Util.getTextSize(labelList[labelList.length - 1], 20)[0] + 50;
      const size = [wrapWidth, wrapWidth];
      const stroke = cfg.style.stroke || "#F69547";
      const keyShape = group.addShape("rect", {
        attrs: {
          width: size[0],
          height: size[1],
          radius: wrapWidth / 2,
          lineWidth: 2,
          lineDash: [5, 5, 5],
          stroke,
        },
        draggable: true,
        name: "root-keyshape",
      });
      group.addShape("rect", {
        attrs: {
          width: width,
          height: width,
          x: 5,
          y: 5,
          radius: width / 2,
          lineWidth: 2,
          stroke,
        },
        draggable: true,
        name: "root-keyshape1",
      });
      labelList?.forEach((label, index) => {
        group.addShape("text", {
          attrs: {
            text: `${label}`,
            fill: "#f89647",
            fontSize: 22,
            fontWeight: 700,
            y:
              labelList.length === 1
                ? width / 2 + 6
                : width / 2 - 8 + index * 26,
            x: width / 2 + 6,
            textAlign: "center",
            textBaseline: "middle",
          },
          draggable: true,
          name: "label-shape",
        });
      });
      return keyShape;
    },
  });

  G6.registerNode("dice-mind-map-sub", {
    draw: (cfg, group) => {
      const labelList = splitStringByMaxLength(cfg.label);
      const width =
        Util.getTextSize(labelList[labelList.length - 1], 20)[0] + 24;
      const stroke = cfg.style.stroke || "#01BEFE";
      const keyShape = group.addShape("rect", {
        attrs: {
          width: width,
          height: width,
          x: 6,
          y: 6,
          radius: width / 2,
          stroke,
        },
        draggable: true,
        name: "root-keyshape",
      });
      labelList?.forEach((label, index) => {
        group.addShape("text", {
          attrs: {
            text: `${label}`,
            fill: "#fff",
            fontSize: 16,
            y:
              labelList.length === 1
                ? width / 2 + 6
                : width / 2 - 2 + index * 18,
            x: width / 2 + 6,
            textAlign: "center",
            textBaseline: "middle",
          },
          draggable: true,
          name: "label-shape",
        });
      });

      return keyShape;
    },
  });
  G6.registerNode("dice-mind-map-leaf", {
    draw: (cfg, group) => {
      const width = Util.getTextSize(cfg.label, 16)[0] + 12;
      const keyShape = group.addShape("rect", {
        attrs: {
          width: width,
          height: 16,
          x: 0,
          y: 0,
          fill: "transparent",
        },
        draggable: true,
        name: "root-keyshape",
      });
      group.addShape("circle", {
        attrs: {
          x: cfg.x < 0 ? width : 0,
          y: 16,
          r: 6,
          fill: "#01BEFE",
        },
        draggable: true,
        name: "root-keyshape",
      });
      group.addShape("text", {
        attrs: {
          text: `${cfg.label}`,
          fill: "#fff",
          fontSize: 16,
          y: 16,
          x: cfg.x < 0 ? 0 : 12,
          textBaseline: "middle",
        },
        draggable: true,
        name: "label-shape",
      });

      return keyShape;
    },
    getAnchorPoints() {
      return [
        [0, 0.965],
        [1, 0.965],
      ];
    },
  });
  const tree = new G6.TreeGraph({
    container: "container",
    fitView: true,
    fitViewPadding: [0, 0],
    layout: {
      type: "mindmap",
      direction: "H",
      getHeight: () => {
        return 12;
      },
      getWidth: (node) => {
        return node.level === 0
          ? Util.getTextSize(node.label, 22)[0] + 12
          : Util.getTextSize(node.label, 16)[0];
      },
      // getVGap: () => {
      //   return 60;
      // },
      getHGap: () => {
        return 50;
      },
      getSide: (node) => {
        return node.data.direction;
      },
    },
    defaultEdge: {
      type: "round-poly",
      // sourceAnchor: 0,
      // targetAnchor: 1,
      style: {
        // radius: 8,
        stroke: "#01BEFE",
      },
    },

    minZoom: 0.9,
    maxZoom: 0.9,
    modes: {
      default: ["drag-canvas", "zoom-canvas", "dice-mindmap"],
    },
  });
  tree.on("node:click", (e) => {
    if (e.item._cfg.model.type === "dice-mind-map-leaf") {
      router.push(
        `/Subject/${e.item._cfg.model.id}/${e.item._cfg.model.label}/MappinKnowledge`
      );
    }
  });

  const num = ref(0);
  const dataTransform = (data) => {
    const oneLevelHalfIndex = Math.ceil(data.children.length / 2);
    const changeData = (d, level = 0, color) => {
      const data = {
        ...d,
      };

      switch (level) {
        case 0:
          data.type = "dice-mind-map-root";
          break;
        case 1:
          data.type = "dice-mind-map-sub";
          break;
        default:
          data.type = "dice-mind-map-leaf";
          break;
      }

      data.hover = false;

      if (color) {
        data.color = color;
      }

      if (level === 1 && !d.direction) {
        num.value++;
        if (!d.direction) {
          data.direction = num.value > oneLevelHalfIndex ? "right" : "left";
        }
      }

      if (d.children) {
        data.children = d.children.map((child) =>
          changeData(child, level + 1, data.color)
        );
      }
      return data;
    };
    return changeData(data);
  };
  const rawData = subjectStore.courseDetail;
  tree.data(dataTransform(rawData));

  tree.render();
});
</script>

<style>
.dice-mind-map-sub {
  cursor: pointer;
}
</style>
